var __jwxa = {
    // 当前页面this对象
    __target: undefined
    },
    // 请求默认设置
    __requestSettings = {
        header: {
            'content-type': 'application/json'
        },
        method: 'GET',
        dataType: 'json',
        success: _empty,
        fail: _empty,
        complete: _empty
    };
// 空函数
function _empty() {}
// url追加参数
function _appendQuery(url, query) {
    if (query == '') return url;
    return (url + '&' + query).replace(/[&?]{1,2}/, '?');
}
// 解析参数
function _parseArguments(url, data, success, fail, dateType) {
    if(__jwxa.isFunction(data)) dateType = fail, fail = success, success = data, data = undefined;
    if(!__jwxa.isFunction(success)) dateType = success, success = undefined;
    if(!__jwxa.isFunction(fail)) dateType = fail, fail = undefined;
    return {
        url: url,
        data: data,
        success: success,
        fail: fail,
        dataType: dateType
    };
}
// 发起wx请求
function _request(options) {
    var settings = options || {};
    for (var key in __requestSettings) {
        if (settings[key] === undefined) settings[key] = __requestSettings[key];
    };
    wx.request(settings);
}

// 是否是函数
__jwxa.isFunction = function(value) {
    return (typeof value) == "function";
}
// 是否是对象
__jwxa.isObject = function(obj) {
    return (typeof obj) == "object";
}
// 当前页面初始化jwxa
__jwxa.jwxa = function(target) {
    /* 初始化清空操作 */
    this.__removeFunction = undefined;
    this.__target = target;
    return this;
}
// get 请求
__jwxa.get = function() {
    return _request(_parseArguments.apply(null, arguments));
};
// post 请求
__jwxa.post = function () {
    var options = _parseArguments.apply(null, arguments);
    options.method = 'POST';
    return _request(options);
}
/*
 设置data{}, 支持点操作符
 说明:
 jwxa.data({key: value}); 相当于this.setData();
 jwxa.data('key1.key2.key3', 'ok'); 相当于设置了{key1: {key2: {key3: 'ok'}}}
 */
__jwxa.data = function(name, value) {
    var data = {};
    data[name] = value;
    // 如果name是一个对象, 直接设置
    this.isObject(name) ? this.__target.setData(name) :  this.__target.setData(data);
    /*
    // @Deprecated 已过时, 发现小程序官方已可优雅设置data
    if(this.isObject(name)) {
        this.__target.setData(name);
    } else {
        var keyArray = name.split(".");
        if(!keyArray && keyArray.length < 1) {
            return ;
        }
            // 根节点Key
        var rootKey = keyArray[0],
            // 下一个节点Key
            nextKey,
            // 根节点对象
            rootObj = keyArray.length == 1 ? value : (this.__target.data[rootKey] || {}),
            // 上一个节点对象
            prevObj = rootObj;
        for(var i=1; i<keyArray.length; ++i) {
            nextKey = keyArray[i];
            prevObj = prevObj[nextKey] = i == keyArray.length - 1 ? value : prevObj[nextKey] || {};
        }
        var dataValue = {};
        dataValue[rootKey] = rootObj;
        this.__target.setData(dataValue);
    }
    */
}
// 字符串解析成JSON对象
__jwxa.parseJSON = JSON.parse;
// 判断空对象
__jwxa.isEmptyObject = function(obj) {
    var name;
    for (name in obj) return false
    return true
}
// 判断空
__jwxa.isEmpty = function (obj) {
    return (this.isNull(obj) || obj === '' || obj.length == 0);
}
// 判断空对象
__jwxa.isNull = function (obj) {
    return (obj === undefined || obj === null);
}
// 设置html
__jwxa.html = function (bindVar, obj) {
    this.isEmpty(bindVar) || this.isEmptyObject(obj) || this.data(bindVar, obj);
    this.__target.jwxaImageTap = function(event) {
        __jwxa.previewImage(obj.imageUrls, event.target.dataset.src);
    };
    return this;
}
// 预览图片( wx.previewImage )
__jwxa.previewImage = function (urls, current) {
    this.isEmpty(current) && (current = urls[0]);
    wx.previewImage({
        current: current, // 当前显示图片的http链接
        urls: urls // 需要预览的图片http链接列表
    })
}
// navigate回退页面( wx.navigateBack )
__jwxa.popToPage = function (delta) {
    this.isEmpty(delta) && (delta = 1);
    wx.navigateBack({
        delta: delta
    })
}
// navigate回退Root页面( wx.navigateBack )
__jwxa.popToRootPage = function () {
    var pages = getCurrentPages();
    this.popToPage(pages.length);
}
// 微信小程序登录( wx.login )
__jwxa.login = function (url, success, fail) {
    if(this.isFunction(url)) fail = success, success = url, url = undefined;
    wx.login({
        success: (url ? function (res) {
            __jwxa.isEmpty(res.code) || __jwxa.get(url, {code: res.code}, success, fail);
        } : success),
        fail: fail
    });
}
// 数据缓存( Storage )
__jwxa.storage = function (key, value, success, fail) {
    if(this.isEmpty(key)) return this;
    if(this.isFunction(value) || this.isObject(key)) fail = success, success = value, value = undefined;
    // getStorage
    if((typeof key == 'string' && this.isNull(value))) {
        return (success ? wx.getStorage({
            key: key,
            success: __jwxa.isFunction(success) ? success : _empty,
            fail: fail
        }) : wx.getStorageSync(key));
    }
    // setStorage, 支持JSON对象格式
    var data = this.isObject(key) ? key : {};
    !this.isObject(key) && (typeof key == 'string') && (data[key] = value);
    for (var dataKey in data) {
        if(success) wx.setStorage({
            key:dataKey,
            data:data[dataKey],
            success: __jwxa.isFunction(success) ? success : _empty,
            fail: fail})
        else wx.setStorageSync(dataKey, data[dataKey])
    }
    return this;
}
// 删除缓存
__jwxa.removeStorage = function (key, success, fail) {
    if(success) wx.removeStorage({
        key: key,
        success: __jwxa.isFunction(success) ? success : _empty,
        fail: fail})
    else wx.removeStorageSync(key)
    return this;
}
// 清空缓存
__jwxa.clearStorage = function (sync) {
    if(sync) wx.clearStorageSync()
    else wx.clearStorage()
    return this;
}

module.exports = __jwxa;